﻿# ----------------- #
# Utility Functions #
# ----------------- #

# Write information message
function Write-Text([string]$message)
{
	Write-Host -ForegroundColor White $message
}

# Write information message
function Write-Information([string]$message, [switch]$noNewline)
{
	Write-Host -ForegroundColor White "[$($(Get-Date).ToString("yyyy-MM-dd HH:mm:ss.fff"))] $message" -NoNewline:$noNewline
}

# Write error message
function Write-Error([string]$message)
{
    Write-Text
	Write-Host -ForegroundColor Red "[$($(Get-Date).ToString("yyyy-MM-dd HH:mm:ss.fff"))] $message"
}

# Start logging
function Start-Logging([string]$logFile)
{
    $Global:IsTranscribing = $false
    if (![string]::IsNullOrEmpty($logFile))
    {
	    Start-Transcript -Path $logFile -Force
        $Global:IsTranscribing = $true
    }
}

# Begin operation
function Begin-Operation([string]$operation, [string]$configFile, [bool]$skipCompleted)
{
	[xml]$Global:Xml = Get-Content -Path $configFile
    $Global:SkipCompleted = $skipCompleted
    [xml]$Global:CompletedOperations = $null
    if ($skipCompleted)
    {
        $Global:CompletedOperationsFile = "$((Get-ChildItem $configFile).FullName).log"
        if (Test-Path -LiteralPath $CompletedOperationsFile)
        {
            [xml]$Global:CompletedOperations = Get-Content -Path $CompletedOperationsFile
        }
        if ($Global:CompletedOperations.configuration.subscriptions -eq $null)
        {
            [xml]$Global:CompletedOperations = [xml]"<?xml version=`"1.0`" ?><configuration><subscriptions /></configuration>"
        }
    }
    Load-AzureModule
    $Global:WindowTitle = $Host.UI.RawUI.WindowTitle
	$Host.UI.RawUI.WindowTitle = "IC.Azure ($operation)"
    Write-Information "Operation '$operation' started."
}

# End operation
function End-Operation([string]$operation)
{
    Write-Information "Operation '$operation' completed."
}

# Finalize operation
function Finalize-Operation
{
    if ($Global:IsTranscribing)
    {
	    Stop-Transcript
    }
    if (![string]::IsNullOrEmpty($Global:WindowTitle))
    {
        $Host.UI.RawUI.WindowTitle = $Global:WindowTitle
    }
}

# Load Azure PowerShell module
function Load-AzureModule
{
    try
    {
        Import-Module Azure
    }
    catch
    {
        throw "Azure PowerShell module is not found."
    }
    if ((Get-Module Azure).Version -lt [Version]::Parse("0.9.0"))
    {
        throw "Azure PowerShell module version '0.9.0' or higher is required."
    }
}

# Check if an element should be executed or skipped
function Should-Run([System.Xml.XmlElement]$element)
{
    if ($element -ne $null -and ($element.run -eq $null -or $element.run -eq $true))
    {
        return $true
    }
    else
    {
        return $false
    }
}